/**
*   Cookie test (servlet)
*   4/6/2012
*/

package org.buptjunjun.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class CookieTest extends HttpServlet
{
    public void doGet(HttpServletRequest request,
                  	 HttpServletResponse response) 
					 throws IOException ,ServletException
	{
		response.setContentType("text/html");	
		PrintWriter out = response.getWriter();	
	
	    //read the cookie from the client
		Cookie [] cookies = request.getCookies();
		//check if the cookie "testCookie is already set"
		String value = getCookieValue(cookies,"testCookie","nullnull");
		
		int current = new Random().nextInt();
		Cookie newCookie = new LongLivedCookie("testCookie","cookie "+current);
		response.addCookie(newCookie);
		
	    out.println("<HTML><BODY>");
		out.println("cookie test<BR>");
		
		if("nullnull".equals(value))
		{
		    out.println("no such cookie");
		}
		else out.println("cookie: name = " + "testCookie" +" ," + "value = "+value +" current value = " +current);
		out.println("</BODY></HTML>");
	
	}

    public void doPost(HttpServletRequest request,
	              HttpServletResponse response)
				  throws IOException, ServletException
	{
	    doGet(request,response);
	}
	
	/**
	*   get the value of certain cookie
	*/
	public String getCookieValue(Cookie[] cookies, 
	                             String cookieName,
								 String defauleValue)
	{
	    if (cookies == null || cookies.length == 0 || cookieName == null)
		   return defauleValue;
		for (int i= 0; i < cookies.length; i++)
		{
		    Cookie cookie = cookies[i];
		    if (cookieName.equals(cookie.getName()))
			{
			    return cookie.getValue();
			}
		}
		
		return defauleValue;
	}
}

